package com.example.demo.common;

import com.example.demo.mapper.WalletLogMapper;
import com.example.demo.mapper.WalletMapper;
import com.example.demo.pojo.Wallet;
import com.example.demo.pojo.WalletLog;
import com.example.demo.vo.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class logAspect {
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private WalletLogMapper walletLogMapper;

    @Pointcut("@annotation(com.example.demo.common.LogAnnotation)")
    public void pointcur() {
    }
    /*
    后置通知
    */
    @AfterReturning(value = "pointcur()",returning = "returnValue")
    public void log(JoinPoint joinPoint, Result returnValue){
        //获取当前时间
        Long l = System.currentTimeMillis();
        Date date = new Date(l);
        //获取当前用户
        Long accountiId=1L;
        //获取钱包
        Wallet wallet = walletMapper.get(accountiId);
        //获取当前方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        //获取当前操作信息
        String operation = annotation.operation();
        WalletLog walletLog = new WalletLog();
        walletLog.setAccountId(accountiId);
        walletLog.setWalletId(wallet.getId());
        walletLog.setCreateTime(date);
        walletLog.setDoSomething(operation);
        String msg = returnValue.getMsg();
        walletLog.setStatus(msg);
        //插入到日志表中
        walletLogMapper.insert(walletLog);
    }
}
